/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: SpecialPathFileHandle.java
 * Author: ckj
 * Date: 2024/7/21 下午9:29
 * Description:
 * 用于处理文件发送事件
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.handle;

import com.bosssoft.issue.BaseIssue;
import com.bosssoft.issue.SpecialPathFileIssue;
import com.bosssoft.message.ReceiveServerFile;
import com.bosssoft.message.ServerMessage;
import com.bosssoft.message.SpecialPathFile;
import com.bosssoft.server.ChatServerWithClientIdentification;
import com.bosssoft.utils.WriterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collections;


/**
 * @author ckj
 */
public class SpecialPathFileHandle implements BaseHandle {

    private static final Logger logger = LoggerFactory.getLogger(SpecialPathFileHandle.class);
    /**
     *
     * @author ckj
     * @date 2024/07/22 上午9:27
     * 处理
     */
    @Override
    public void handle(BaseIssue issue) throws IOException {
        SpecialPathFileIssue specialPathFileIssue = (SpecialPathFileIssue) issue;
        SpecialPathFile message = (SpecialPathFile) specialPathFileIssue.getMessage();
        ReceiveServerFile receiveServerMessage = new ReceiveServerFile().sendMessageBuild(message.getFileName(), message.getFileContent());
        try {
            WriterUtil.writeToUser(specialPathFileIssue.getWriter(), ServerMessage.fileIsBeingReceived().convertFromTransferableDataList());
        } catch (Exception e) {
            logger.error("输入失败");
        }
        if (ChatServerWithClientIdentification.getClientMap().containsKey(message.getTargetUserName())){
            Socket targetUserSocket = ChatServerWithClientIdentification.getClientMap().get(message.getTargetUserName()).getSocket();
            try {
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(targetUserSocket.getOutputStream()), true);
                WriterUtil.writeToUser(writer,receiveServerMessage.convertFromTransferableDataList());
                WriterUtil.writeToUser(specialPathFileIssue.getWriter(),ServerMessage.fileIsReceived().convertFromTransferableDataList());
            } catch (Exception e) {
                logger.error("输入失败");
            }
        } else {
            ChatServerWithClientIdentification.getMessageMap().put(message.getTargetUserName(), Collections.singletonList(receiveServerMessage));
            try {
                WriterUtil.writeToUser(specialPathFileIssue.getWriter(),ServerMessage.fileIsReceived().convertFromTransferableDataList());
            } catch (Exception e) {
                logger.error("输入失败");
            }
        }

    }
}